<template>
<!--  评论-->
  <el-card>
    <el-row>
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-right: 10px" @click="handleBulkDelete">批量删除</el-button>
      <el-input v-model="data.keyword" placeholder="姓名" style="width: 200px; margin-right: 10px">
        <template #prefix>
          <el-icon class="el-input__icon">
            <search/>
          </el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="warning" @click="handleEmpty">清空</el-button>
    </el-row>
    <el-table
        v-loading="data.loading === true"
        :data="data.tableData"
        style="width: 100%; margin-top: 10px; overflow: hidden"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" sortable ></el-table-column>
      <el-table-column prop="id" label="序号" sortable min-width="100"></el-table-column>
      <el-table-column prop="cover" label="头像" min-width="150">
        <template v-slot="scope">
          <!-- 这里假设cover字段存储的是头像的URL -->
          <img @error="handleImageError(scope.row)" :src="scope.row.cover" alt="" style="width: 40px; height: 40px; border-radius: 50%;">
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" sortable min-width="150"></el-table-column>
      <el-table-column prop="sex" label="性别" sortable min-width="100"></el-table-column>
      <el-table-column prop="birthday" label="出生日期" sortable min-width="150"></el-table-column>
      <el-table-column prop="education" label="学历" sortable min-width="150"></el-table-column>
      <el-table-column prop="school" label="毕业学校" sortable min-width="200"></el-table-column>
      <el-table-column label="操作" min-width="150">
        <template #default="scope">
          <el-button-group>
            <el-button size="default" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="data.total" style="margin-top: 10px">
      <el-pagination
          background
          small
          :page-size="data.pageSize"
          :current-page="data.pageNum"
          layout="total,prev, pager, next,jumper"
          :total="data.total"
          @current-change="handleCurrentChange"
      ></el-pagination>
    </div>


    <!--    弹窗-->
    <el-dialog v-model="data.formVisible" title="简历信息" width="50%" destroy-on-close>
      <el-form
          :model="data.form"
          label-width="120px"
          ref="ruleFormRef"
          :rules="data.rules"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="data.form.name" placeholder="请输入"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="性别" prop="sex">
              <el-select
                  v-if="data.formVisible"
                  v-model="data.form.sex"
                  clearable
                  placeholder="请选择">
                <el-option key="男" value="男">男</el-option>
                <el-option key="女" value="女">女</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col>
          <el-form-item label="头像" >
            <el-upload
                :action="uploadUrl"
                :limit="1"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-row>
          <el-col :span="10">
            <el-form-item label="出生日期" prop="birthday">
              <el-input v-model="data.form.birthday" placeholder="例：2000-05-01"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="学历" prop="education">
              <el-select
                  v-if="data.formVisible"
                  v-model="data.form.education"
                  clearable
                  placeholder="请选择">
                <el-option key="专科" value="专科">专科</el-option>
                <el-option key="本科" value="本科">本科</el-option>
                <el-option key="研究生" value="研究生">研究生</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="10">
          <el-form-item label="毕业学校" prop="school">
            <el-input v-model="data.form.school" placeholder="请输入"/>
          </el-form-item>
        </el-col>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Formcancel">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>



<script setup>

import {computed, onMounted, reactive, ref} from "vue";
import {createApi, deleteApi, listApi, updateApi} from "@/api/resum";
import {ElMessage, ElMessageBox} from "element-plus";
import { BASE_URL } from "@/store/constants"
import {deleteFile} from "@/api/file";
import defaultAvatar from "@/assets/icons/defaultAvatar.png";
import {Search} from "@element-plus/icons-vue";
// 在计算属性中拼接URL
const uploadUrl = computed(() => {
  return `${BASE_URL}/api/files/upload`;

});
const data=reactive({
  tableData:[],
  loading:false,
  formVisible:false,
  editFlag:false,
  total:0,
  pageNum:1,
  pageSize:9,
  titles:[{}],
  selectedItems: [], // 添加这个来存储被选中的行的详细信息
  keyword:'',
  form:{
    id:'',
    cover:'',
    name:'',
    sex: '',
    raw:'',
    education: '',
    school: '',
    email: '',
    mobile: '',
    userId: '',
    birthday: '',
    oldCover:'',
  },
  rules:{
    name: [{ required : true, message : '请选择', trigger : 'blur'}],
    sex: [{ required : true, message : '请输入评论内容', trigger : 'blur'}]
  }
})
const handleImageError = (row) => {
  row.cover = defaultAvatar;
};
const handleAvatarSuccess = (file) => {
  try {
    if (file.code===200){
      data.form.cover=file.data; // 将后端返回的头像URL保存到表单的cover字段
      ElMessage.success(file.msg);
    }else{
      ElMessage.error('错误');
    }
  }catch (err){
    console.error(file.msg);
  }
}

// 定义beforeAvatarUpload函数以限制上传
const beforeAvatarUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传的图片大小不能超过2MB！');
    return false;
  }
  return true;
};

onMounted(()=>{
  getDataList();

})
const getDataList=()=>{
  data.loading=true;
  setTimeout(() => {
    data.loading = false;
  }, 1000);
  listApi({
    pageNum:data.pageNum,
    pageSize:data.pageSize,
    keyWord:data.keyword,
  }).then(res=>{
    // console.log(res);
    data.tableData=res.data.list;
    data.total=res.data.total;
    data.pageNum=res.data.pageNum;
    data.pageSize=res.data.pageSize;

    // 新增逻辑：遍历tableData，构建包含thingId和title的对象数组
    const titlesWithIds = data.tableData.map(item => ({ thingId: item.thingId, title: item.title }));

    // 去重逻辑：使用Set去重（基于JSON.stringify和JSON.parse确保对象的可比较性）
    data.titles = Array.from(new Set(titlesWithIds.map(JSON.stringify))).map(JSON.parse);
    // console.log(data.titles)
  }).catch(err=>{
    console.log(err);
  })
}
const handleAdd=()=>{
  data.formVisible=true;
}
const Formcancel=async () => {
  // console.log(data.form.cover);
  if (data.form.cover !== data.form.oldCover) { // 检查是否有新上传的图片
    // 删除新上传的图片
    await deleteTemporaryImage(data.form.cover);
    // 还原cover为旧图片URL
    data.form.cover = data.form.oldCover;
  }
  data.form = {};
  data.formVisible = false;
  data.editFlag=false;
  getDataList();
}

async function deleteTemporaryImage(url) {
  await deleteFile({ fileUrl: url }).then(res=>{
    if (res.code===200){
      ElMessage.success('图片已删除');
    }else {
      ElMessage.error('删除图片出错');
    }
  }).catch(err=>{
    console.error(err);
  })
}
async function deleteOldCover(oldCoverUrl) {
  try {
    await deleteTemporaryImage(oldCoverUrl);
    ElMessage.success('旧头像已删除');
  } catch (error) {
    console.error('删除旧头像出错:', error);
    ElMessage.error('删除旧头像失败');
  }
}
const ruleFormRef = ref()
const save=async () => {
  try {
    //验证表单
    const isValid = await ruleFormRef.value.validate();
    if (!isValid) {
      return;
    }
    // 在成功保存新数据后，如果处于编辑模式且有旧头像，则删除
    if (data.editFlag && data.form.oldCover) {
      await deleteOldCover(data.form.oldCover);
    }
    if (data.form.id) {
      updateApi(data.form).then(res => {
        // console.log(res)
        if (res.code === 200) {
          ElMessage.success(res.msg);
          data.form = {};
          data.formVisible = false;
          getDataList();
        } else {
          ElMessage.error(res.msg);
        }
      })
    } else {
      data.form.userId=localStorage.getItem('admin_user_id');
      createApi(data.form).then(res => {
        // console.log(res)
        if (res.code === 200) {
          ElMessage.success(res.msg);
          data.form = {};
          data.formVisible = false;
          getDataList();
        } else {
          ElMessage.error(res.msg);
        }
      })
    }
  } catch (err) {
    console.error(err);
  }
}

const handleEdit = (row) => {
  data.editFlag=true;
  data.form=row;
  data.form.oldCover = row.cover; // 保存旧头像URL
  data.formVisible=true;
}
const handleDelete = (row) => {
  ElMessageBox.confirm('删除后数据无法恢复，确认删除？','警告',{type:'warning'})
      .then(()=>{
        deleteTemporaryImage(data.form.cover);
        deleteApi({'ids':row.id}).then(res=>{
          if (res.code===200){
            ElMessage.success('删除成功')
            getDataList();
          }else {
            ElMessage.error(res.msg)
          }
        })
      }).catch(err=>{
    console.error('请求错误',err);
    ElMessage.info('取消');
  })
}
const handleSelectionChange=(selection)=>{
  data.selectedIds = selection.map(item => item.id);
  // 更新selectedItems数组，这里我们直接使用selection，因为它已经包含了选中行的完整信息
  data.selectedItems = selection;
}
const handleBulkDelete = () => {

  if (data.selectedIds === undefined || data.selectedIds.length === 0) {
    ElMessage.warning('请选择要删除的标签')
    return;
  }
  // 将数组转换为逗号分隔的字符串
  const idsParam = data.selectedIds.join(',');
  ElMessageBox.confirm('确认删除选中的标签吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 假设data.selectedItems是一个包含选中项详细信息的数组
      for (const itemId of data.selectedIds) {
        const item = data.selectedItems.find(item => item.id === itemId);
        if (item && item.cover) {
          await deleteTemporaryImage(item.cover);
        }
      }

      // 所有封面图片删除成功后，再删除数据
      const res = await deleteApi({'ids': idsParam});
      if (res.code === 200) {
        ElMessage.success(res.msg);
        await getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    } catch (error) {
      console.error('删除过程中出现错误:', error);
      ElMessage.error('删除操作失败，请重试');
    }
  }).catch(err => {
    console.error(err);
  })
}
const handleCurrentChange = (number) => {
  data.pageNum=number;
  getDataList();
}

const handleSearch=()=>{
  getDataList()
}

const handleEmpty=()=>{
  data.keyword='';
  getDataList();
}
</script>


<style scoped>

</style>

